#pragma once
#include <iostream>
#include <functional>
template<class T>
class SmartPtr
{
public:
	SmartPtr(T* ptr)
	{
		_ptr = ptr;
	}

	~SmartPtr()
	{
		std::cout << "~SmartPtr()" << _ptr << std::endl;
		delete _ptr;
	}

	T& operator*()
	{
		return *_ptr;
	}

	T* operator->()
	{
		return _ptr;
	}

private:
	T* _ptr;
};


namespace ljt
{
	template<class T>
	class unique_ptr
	{
	public:
		unique_ptr(T* ptr)
			:_ptr(ptr)
		{}
		~unique_ptr()
		{
			std::cout << "~unique_ptr()" << _ptr << std::endl;
			delete _ptr;
		}
		T& operator*()
		{
			return *_ptr;
		}

		T* operator->()
		{
			return _ptr;
		}

		//C++11
		unique_ptr(const unique_ptr<T>& up) = delete;
		unique_ptr<T> operator=(const unique_ptr<T>& up) = delete;
	private:
		T* _ptr;
	};

	template<class T>
	class shared_ptr
	{
	public:
		shared_ptr(T* ptr)
			:_ptr(ptr), _pcount(new int(1))
		{}

		template <class D>
		shared_ptr(const shared_ptr<T>& sp, D del)
			:_ptr(sp._ptr), _pcount(sp._pcount), _del(del)
		{
			(*_pcount)++;
		}
		~shared_ptr()
		{
			release();
		}
		void release()
		{
			if (--(*_pcount) == 0)
			{
			/*	delete _ptr;
				delete _pcount;*/
				_del(_ptr);
			}
		}

		shared_ptr<T>& operator=(shared_ptr<T>& sp)
		{
			if (_ptr != sp._ptr)
			{
				release();

				_ptr = sp._ptr;
				_pcount = sp._pcount;

				(*_pcount)++;
			}

			return *this;
		}

		T* getPtr() const 
		{
			return _ptr;
		}

		int count()
		{
			return *_pcount;
		}
		T& operator*()
		{
			return *_ptr;
		}

		T* operator->()
		{
			return _ptr;
		}

	private:
		T* _ptr;
		int* _pcount;
		std::function<void(T*)> _del = [](T* ptr) {delete ptr; };
	};

	template<class T>
	class weak_ptr
	{
	public:
		weak_ptr()
			:_ptr(nullptr)
		{}

		weak_ptr(const shared_ptr<T>& sp)
			:_ptr(sp.getPtr())
		{}

		weak_ptr<T>& operator=(const shared_ptr<T>& sp)
		{
			_ptr = sp.getPtr();

			return *this;
		}

		T& operator*()
		{
			return *_ptr;
		}

		T* operator->()
		{
			return _ptr;
		}
	private:
		T* _ptr;
	};
};
